<?php
apf_require_controller('Abstract');
apf_require_class("Login_Ldap");
apf_require_class("Util_Encrypt");
apf_require_class("Util_Cookie");
apf_require_class("Bll_Jx_Log");
class Login_InController extends AbstractController {

    private $bll;
    private $data;//post参数
    //上次访问的url
    private $keep = '';


    public function handle_request() {
        $oauth = APF::get_instance()->get_config('oauth_info');
        if ($oauth){
            $status = $this->handle_request_new($oauth);
        }else{
            $status = $this->handle_request_old();
        }
        return "Login_In";
    }
    public function check_oa_user($user){
        if(!empty($user)){
            return true;
        }
        echo "<script>alert('员工信息未同步到OA系统中,请联系IT');</script>";exit;
    }
    /*********************** 老版(本地)登陆方式 ***********************/
    /**
     * 直接连接域名服务器验证用户信息
     *
     * **/
    public function handle_request_old() {
        if('post' == strtolower($_SERVER['REQUEST_METHOD'])){
            $this->data = $this->request->get_parameters();
        }
        if(isset($_GET['back']) && $_GET['back']) {
            $this->keep = base64_decode($_GET['back']);
        }
        if(!empty($this->data['user_name']) && !empty($this->data['user_psw'])){
            //提交认证
            $check = $this->login($this->data['user_name'], $this->data['user_psw']);
            if(!$check){
                $this->request->set_attribute('login_msg','用户名或密码错误');
            }else{
                //跳转到～登陆前的页面
                $url = Util_JxUrls::base_url();
                $this->response->redirect($url,false,false);
            }
        }else{
            $this->request->set_attribute('login_msg','用户名和密码不能为空');
        }
        return true;
    }
    /**
     * 用户登录
     */
    public function login($user_name,$user_psw){
        $info = Login_Ldap::get_instance($user_name, $user_psw);
        if($info->get_bind()){
            //登录成功
            $user_ldap = $info->getinfo();
            $user_info = $this->oahr->get_user_base_info($user_ldap['code'],1);
            $this->check_oa_user($user_info);
            Util_Cookie::set_cookie($user_info);
            $log=new Bll_Jx_Log();
            $log->get_login_user_info($this->request->get_user_id(),$user_ldap["chinese_name"],APF::get_instance()->get_request()->get_client_ip());
            return $user_info;
        }
        return false;
    }
    private function _set_cookie($user_info){

    }
    /*********************** 老版(本地)登陆方式 ***********************/

    /**
     * 使用oauth 认证登陆
     * **/
    public function handle_request_new($outh) {
        if(isset($_GET['back']) && $_GET['back']) {
            $_SESSION['oauth_use_backurl'] = base64_decode($_GET['back']);
        }
        $info = $this->login_with_oauth($outh['client_id'], $outh['client_secret'], $outh['oauth_url']);
        if(!$info){
            echo "<script>alert('Oauth登录失败，请重试，或与IT联系');</script>";
            $this->response->redirect($url,false,false);exit;
        }
        $info = json_decode($info,true);
        extract($info);
        /*检查用户是否注册，未注册，则继续获取详细信息*/
        $info = $this->get_info_from_ldap($access_token, $outh['oauth_url']);
        if(!$info){
            echo "<script>alert('域信息获取失败，请与IT联系！');</script>";
            $this->response->redirect($url,false,false);exit;
        }
        //使用登陆前的url
        $this->keep = $_SESSION['oauth_use_backurl'];
        unset($_SESSION['oauth_use_backurl']);
        $info = json_decode($info,true);
        $this->check_login_by_oauth($info['staff_no']);
        return false;
    }

    /**
     * Oauth 认证方式
     * @param $code 员工号
     * **/
    private function check_login_by_oauth($code){
        //进行认证
        $data = $this->data;
        $check = $this->login_by_oauth($code);
        $url = "http://".$_SERVER['HTTP_HOST'].'/';
        if(!$check){
            echo "<script>alert('没有对应的员工信息');</script>";
            $this->response->redirect($url,false,false);
        }
        else{
            //跳转到～登陆前的页面
            if($this->keep && preg_match('/'.$_SERVER['HTTP_HOST'].'/',$this->keep)) {
                $url = $this->keep;
            }
            if(preg_match('/login/', $url)){
                $url = 'http://jx.corp.anjuke.com';
            }
            $this->response->redirect($url,false,false);exit;
        }
    }

    /**
     * 用户登录
     */
    public function login_by_oauth($code){
        $result = array();
        if($code){
            //登录成功
            $user_info = $this->oahr->get_user_info_by_code($code);
            $this->check_oa_user($user_info);
            if(empty($user_info)) {
                return $result;
            }
            //写cookie
            Util_Cookie::set_cookie($user_info);
            //$log=new Bll_Jx_Log();
            //$log->get_login_user_info($this->request->get_user_id(),$user_ldap["chinese_name"],APF::get_instance()->get_request()->get_client_ip());
            return $user_info;
        }
        return $result;
    }

   /**
    * 用户身份认证，
    * 成功则返回用户域账户名和访问令牌
    * oauth
    */
    function login_with_oauth($client_id, $client_secret, $oauth_url){
        if(isset($_REQUEST['code']) && $_REQUEST['code']){
            /*2、用临时令牌，申请访问令牌*/
            $data = array(
                "client_id"=>$client_id,
                "client_secret"=>$client_secret,
                "grant_type"=>'authorization_code',/*默认*/
                "code"=>$_REQUEST['code'],/*临时令牌*/
            );

            header("HTTP/1.1 302 Found");
            header("Location: " . $oauth_url.'/token.php?'.http_build_query($data));
            exit();

        }
        if(isset($_REQUEST['access_token']) && $_REQUEST['access_token']){
            /*3、用AccessToken,获取info*/
            $access_token = $_REQUEST['access_token'];

            $data = array(
                    "oauth_token"=>$access_token,/*只要一个$access_token，是不是很危险？？*/
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $oauth_url."/resource.php");
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $info = curl_exec($ch);
            if($info) return $info;
            else return false;
            exit();
        }
        /*1、获取临时令牌RequestToken*/
        header("HTTP/1.1 302 Found");
        $array = array(
                "client_id"=>$client_id,
                "response_type"=>"code"/*默认*/
        );
        header("Location: " . $oauth_url.'/authorize.php?'.http_build_query($array));
        exit;
    }

    /**
     * 用户注册流程，
     * 用访问令牌到oauth获取用户详细信息
     */
    function get_info_from_ldap($access_token, $oauth_url){
        $data = array(
                "oauth_token"=>$access_token,
                "getinfo"=>true,
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $oauth_url."/resource.php");
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $info = curl_exec($ch);
        if($info) return $info;
        else return false;
    }

    private function get_user_bll(){
        if (!$this->user_bll || !$this->user_bll instanceof Bll_Login_User){
            apf_require_class('Bll_Login_User');
            $this->user_bll = new Bll_Login_User();
        }
        return $this->user_bll;
    }

}
